#include "../source/server.hpp"
static uint64_t conn_id = 0;
EventLoop base_loop;
std::unordered_map<uint64_t, PtrConnection> _conns;
LoopThreadPool* loop_pool;

void ConnectionDestroy(const PtrConnection& conn)
{
    _conns.erase(conn->Id()); 
}
void OnConnected(const PtrConnection& conn)
{
    DBG_LOG("NEW CONNECTION: %p", conn.get());
}
void OnMessage(const PtrConnection& conn, Buffer* buf)
{
    DBG_LOG("%s", buf->ReadPosition());
    buf->MoveReadOffset(buf->ReadableSize());
    std::string str = "hello linux";
    conn->Send(str.c_str(), str.size());
}

void Accepter(int newfd)
{
    conn_id++;
    std::shared_ptr<Connection> conn(new Connection(loop_pool->NextLoop(), conn_id, newfd));
    conn->SetConnectedCallBack(std::bind(OnConnected, std::placeholders::_1));
    conn->SetSvrClosedCallBack(std::bind(ConnectionDestroy, std::placeholders::_1));
    conn->SetMessageCallBack(std::bind(OnMessage, std::placeholders::_1, std::placeholders::_2));
    conn->EnableInactiveRelease(10);
    conn->Established();
    _conns.insert(std::make_pair(conn_id, conn));
    DBG_LOG("NEW-------------------------");
}

int main()
{
    loop_pool = new LoopThreadPool(&base_loop);
    loop_pool->SetThreadCount(5);
    loop_pool->Create(); 
    Acceptor acceptor(&base_loop, 8080);
    acceptor.SetAcceptCallBack(Accepter);
    acceptor.Listen();
    base_loop.Start();
    return 0;
}